package com.coocaa.x.app.liteplayer.ui;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.cyberplayer.core.BVideoView;
import com.coocaa.x.app.liteplayer.R;
import com.coocaa.x.app.liteplayer.ui.widget.LoadingView;
import com.coocaa.x.app.liteplayer.ui.widget.PlayProgressBar;
import com.coocaa.x.app.liteplayer.ui.widget.TipToast;

public class PlayerView extends FrameLayout {
    private static final String tag = "pv";
    private Context mContext;
    //    private SurfaceView surfaceView;
    private BVideoView mBVideoView;
    private FrameLayout panelLayout;
    private TextView titleText;
    private TextView timeText;
    private LinearLayout floatTimeLayout;
    private TextView floatTimeText;
    private ImageView arrowImage;
    private PlayProgressBar progressBar;
    private LoadingView loadingView;
    private PlayerTipView tipView;

    private int duration;
    private String durationStr = "--:--";
    private int crtProgress;
    private int secondProgress;

    private int TimeTextSize = SkyConstants.Dpi(25);
    private int TitleTextSize = SkyConstants.Dpi(28);
    private int TipTextSize = SkyConstants.Dpi(23);
    private int PausedTextSize = SkyConstants.Dpi(60);
    private int dotSize = SkyConstants.Div(30);
    private int progressBarHeight = SkyConstants.Div(8);
    private int floatTimeHeight = SkyConstants.Div(84);

    private boolean panelDisplayed = false; // 播放面板是否显示
    private boolean pressToExit = false; // 距当前时间3s内是否按过一次退出键
    private boolean seekCalled = false; // 是否从电视端调用了seek（seek命令还有可能从手机端发出）
    private boolean paused = false; // 当前是否暂停
    private boolean netConnected = true; // 当前网络状态是否正常
    private boolean isSndPgsChanged = false; // 是否手动调整了播放进度

    private int panelShowInterval = 5000;
    private int waitToSeekInterval = 800; // 调整进度后等800ms进行seek
    private int doubleClickExitInterval = 3000;
    private int tipInterval = 3000;
    //    private int closeToEndDuration = 5999; // 视频播完前几ms内给出“即将播放完毕”提示
    //调整为秒单位
    private int closeToEndDuration = 6; // 视频播完前几s内给出“即将播放完毕”提示

    private boolean closeToEndTipShown = false;

    private PowerManager.WakeLock wakeLock;
    public int videoType = 3;

    private String AK = "DRGfRCVks9H7FIZsLsna0ShP";
    private String SK = "EjiGkL8F6y7Xssoq";

    private boolean needExitActivity = true;

    public static enum ERROT_TYPE {
        PARSE_ERROR,
        LIVE_UNSUPPORT_ERROR,
        UNKNOWN_ERROR
    }

    ;

    public PlayerView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        this.mContext = context;
        createView();
//        NetChangeReceiver.addListener(this);

        PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "appstore_player");
    }

    public BVideoView getBVV() {
        return mBVideoView;
    }

    private void createView() {
        BVideoView.setAKSK(AK, SK);
        mBVideoView = new BVideoView(mContext);
//        mBVideoView.setDecodeMode(BVideoView.DECODE_SW);
        mBVideoView.setDecodeMode(BVideoView.DECODE_HW);
        mBVideoView.showCacheInfo(false);
        this.addView(mBVideoView, new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT));
        mBVideoView.setVisibility(View.INVISIBLE);

        initTipText();

        panelLayout = new FrameLayout(mContext);
        this.addView(panelLayout, new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT, Gravity.BOTTOM));
        panelLayout.setVisibility(View.INVISIBLE);

        LayoutParams downParams = new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT, Gravity.BOTTOM);
        downParams.topMargin = (dotSize + progressBarHeight) / 2 + floatTimeHeight;
        panelLayout.addView(initDownLayout(), downParams);

        initProgressBar();
        initFloatTimeText();

        initLoadingView();
    }

    public void showBVV(boolean isShow) {
        if (isShow)
            mBVideoView.setVisibility(View.VISIBLE);
        else
            mBVideoView.setVisibility(View.INVISIBLE);
    }

    private void initProgressBar() {
        progressBar = new PlayProgressBar(mContext);
        progressBar.setBarHeight(progressBarHeight);
        progressBar.setDotSize(dotSize);
        LayoutParams progressParams = new LayoutParams(LayoutParams.WRAP_CONTENT, dotSize,
                Gravity.TOP);
        progressParams.topMargin = floatTimeHeight;
        panelLayout.addView(progressBar, progressParams);
    }

    private void initFloatTimeText() {
        floatTimeLayout = new LinearLayout(mContext);
        floatTimeLayout.setOrientation(LinearLayout.VERTICAL);

        floatTimeText = newTextView(TimeTextSize,
                mContext.getResources().getColor(R.color.playerTimeColor));
        floatTimeText.setBackgroundColor(SkinManager.getColor(R.color.floatTimeBgColor));
//        SkinManager.setBackground(floatTimeText, R.drawable.float_time_bg);
        floatTimeText.setPadding(SkyConstants.Div(28), SkyConstants.Div(9), SkyConstants.Div(28),
                SkyConstants.Div(9));
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);
        params.setMargins(0, 0, 0, 0);
        floatTimeLayout.addView(floatTimeText, params);

        arrowImage = new ImageView(mContext);
        SkinManager.setBackground(arrowImage, R.drawable.arrow_down);
        LinearLayout.LayoutParams arrowParams = new LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        arrowParams.setMargins(0, 0, 0, 0);
        floatTimeLayout.addView(arrowImage, arrowParams);

        panelLayout.addView(floatTimeLayout, new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT, Gravity.TOP));
        floatTimeLayout.setVisibility(View.INVISIBLE);
    }

    private ViewGroup initDownLayout() {
        FrameLayout layout = new FrameLayout(mContext);
        layout.setBackgroundColor(mContext.getResources().getColor(R.color.playerPanelBgColor));
        layout.setPadding(SkyConstants.Div(36), SkyConstants.Div(15), SkyConstants.Div(36),
                SkyConstants.Div(15));

        timeText = newTextView(TimeTextSize,
                mContext.getResources().getColor(R.color.playerTimeColor));
        LayoutParams timeParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL);
        timeParams.bottomMargin = SkyConstants.Div(25);
        timeParams.leftMargin = SkyConstants.Div(40);
        layout.addView(timeText, timeParams);

        titleText = newTextView(TitleTextSize,
                mContext.getResources().getColor(R.color.playerTitleColor));
        titleText.setCompoundDrawablePadding(SkyConstants.Div(15));
        titleText.setCompoundDrawablesWithIntrinsicBounds(R.drawable.play_icon, 0, 0, 0);
        titleText.setPadding(0, 0, 0, SkyConstants.Div(10));
        LayoutParams titleParams = new LayoutParams(SkyConstants.Div(1000),
                LayoutParams.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL);
        titleParams.topMargin = SkyConstants.Div(25);
        layout.addView(titleText, titleParams);

        LinearLayout rightLayout = new LinearLayout(mContext);
        layout.addView(rightLayout, new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT, Gravity.RIGHT | Gravity.CENTER_VERTICAL));

        rightLayout.addView(newTipTextView(R.drawable.key_ok, R.string.tip_play));
        rightLayout.addView(newTipTextView(R.drawable.key_updown, R.string.tip_updown));
        rightLayout.addView(newTipTextView(R.drawable.key_leftright, R.string.tip_leftright));

        return layout;
    }

    private void initTipText() {
        tipView = new PlayerTipView(mContext);
        this.addView(tipView,
                new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        tipView.setVisibility(View.INVISIBLE);
    }

    private void initLoadingView() {
        loadingView = new LoadingView(mContext);
        this.addView(loadingView, new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT));
        loadingView.setLoadingText(mContext.getString(R.string.player_loading));
        Log.d(tag, "initLoadingView  startloading");
        startLoading();
    }

    private TextView newTextView(int textSize, int textColor) {
        TextView text = new TextView(mContext);
        text.setTextSize(textSize);
        text.setTextColor(textColor);
        text.setSingleLine();
        return text;
    }

    private TextView newTipTextView(int leftDrawableResId, int strId) {
        TextView text = newTextView(TipTextSize,
                mContext.getResources().getColor(R.color.playerTipColor));
        text.setCompoundDrawablesWithIntrinsicBounds(leftDrawableResId, 0, 0, 0);
        text.setCompoundDrawablePadding(SkyConstants.Div(10));
        text.setPadding(SkyConstants.Div(70), 0, 0, 0);
        text.setSingleLine();
        text.setText(strId);
        return text;
    }


    private void refreshProgressBar() {
        Log.d(tag, "refreshProgressBar crtProgress:" + crtProgress + " duration:" + duration);
        if (duration == 0)
            progressBar.setRealProgress(0);
        else {
            float percent = (float) crtProgress / (float) duration;
            Log.d(tag, "refreshProgressBar  percent:" + percent);
            progressBar.setRealProgress(percent);
        }
    }

    private void showPanel() {
        if (panelDisplayed)
            return;
        if (!netConnected) // 未联网情况下不允许显示面板
            return;
        timeText.setText(String.format("%s/%s", formatTime(crtProgress), durationStr));
        refreshProgressBar();
        int panelPosY = this.getMeasuredHeight() - panelLayout.getMeasuredHeight();
        secondProgress = crtProgress;
        panelLayout.animate().y(panelPosY).setDuration(300);
        if (timeHandler.hasMessages(HIDE_PANEL_MSG_ID))
            timeHandler.removeMessages(HIDE_PANEL_MSG_ID);
        timeHandler.sendEmptyMessageDelayed(HIDE_PANEL_MSG_ID, panelShowInterval);
        panelDisplayed = true;
    }

    private void hidePanel() {
        isSndPgsChanged = false;
        if (!panelDisplayed)
            return;
        panelLayout.animate().y(this.getMeasuredHeight()).setDuration(300);
        panelDisplayed = false;
        floatTimeLayout.setVisibility(View.INVISIBLE);
    }

    private void delayPanelDisappear() {
        if (timeHandler.hasMessages(HIDE_PANEL_MSG_ID))
            timeHandler.removeMessages(HIDE_PANEL_MSG_ID);
        timeHandler.sendEmptyMessageDelayed(HIDE_PANEL_MSG_ID, panelShowInterval);
    }

    public void onSeekComplete() {
        Log.i(tag, "seekComplete");
        seekCalled = false;
        timeHandler.sendEmptyMessage(SEEK_COMPLETE);
        Log.i("pppp", "onSeekComplete  ");
        progressBar.hideSecondProgress();
        if (paused && playerExecutor != null)
            playerExecutor.resume();
    }

    public void seekComplete() {
        Log.i("pppp", "seekComplete  ");
        progressBar.hideSecondProgress();
    }

    public void onProgressChanged(int timeInMilliSeconds) {
        // TODO Auto-generated method stub
        Log.i(tag, "!!onProgressChanged, time = " + timeInMilliSeconds + " videoType:"
                + videoType);
        Message msg = timeHandler.obtainMessage(PROGRESS_CHANGED);
        msg.arg1 = timeInMilliSeconds;
        timeHandler.sendMessage(msg);
    }

    public void progressChanged(int timeInMilliSeconds) {
        // TODO Auto-generated method stub
        if (duration > 0 && (duration - timeInMilliSeconds) <= closeToEndDuration
                && !closeToEndTipShown) {
            String endStr = mContext.getString(R.string.play_close_to_end);
            if (playerExecutor != null && playerExecutor.hasNext()) {
                endStr = mContext.getString(R.string.play_close_to_next);
            }
            TipToast.getInstance(mContext).showToast(
                    SkinManager.getResDrawable(R.drawable.toast_icon_tip), endStr, tipInterval,
                    Gravity.BOTTOM);
            closeToEndTipShown = true;
        }
        crtProgress = timeInMilliSeconds;
        if (!panelDisplayed)
            return;
        timeText.setText(String.format("%s/%s", formatTime(timeInMilliSeconds), durationStr));
        Log.d(tag, "progressChanged  timeInMilliSeconds:" + timeInMilliSeconds);
        refreshProgressBar();
    }

    public void onPlayStarted(String videoName, int durationInMilliSeconds) {
        // TODO Auto-generated method stub
        Log.i(tag, "----------play started, videoName = " + videoName + ", duration = "
                + durationInMilliSeconds);
        pressToExit = false;
        paused = false;
        closeToEndTipShown = false;

        Message msg = timeHandler.obtainMessage(PLAY_STARTED);
        msg.arg1 = durationInMilliSeconds;
        msg.obj = videoName;
        timeHandler.sendMessage(msg);

        wakeLock.acquire();
    }

    public void playStarted(String videoName, int durationInMilliSeconds) {
        // TODO Auto-generated method stub
        titleText.setText(videoName);
        this.duration = durationInMilliSeconds;
        this.durationStr = formatTime(durationInMilliSeconds);
        crtProgress = 0;
        timeText.setText(String.format("00:00/%s", durationStr));
        tipView.hideTip();
        panelLayout.setVisibility(View.VISIBLE);
        showPanel();
        Log.i(tag, "play start stop loading");
        stopLoading();
    }

    public void onPlayResumed() {
        // TODO Auto-generated method stub
        Log.i(tag, "play resumed");
        paused = false;
        timeHandler.sendEmptyMessage(PLAY_RESUMED);
    }

    public void playResumed() {
        // TODO Auto-generated method stub
        tipView.hideTip();
    }

    public void onPlayPaused() {
        // TODO Auto-generated method stub
        Log.i(tag, "play paused");
        paused = true;
        timeHandler.sendEmptyMessage(PLAY_PAUSED);
    }

    public void playPaused() {
        // TODO Auto-generated method stub
        // showPauseTip();
        if (exitPlayerCalled)
            return;
        tipView.showPauseStatus();
        Log.i(tag, " playpause stop loading");
        loadingView.stopLoading();
        showPanel();
    }

    public void onPlayStopped() {
        Log.i(tag, "play stopped");
        pressToExit = true;

        timeHandler.sendEmptyMessage(PLAY_STOPPED);
        try {
            wakeLock.release();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    public boolean onInfo(int what, int extra) {
        // TODO Auto-generated method stub
        Log.i("bvv", "!!!info, what = " + what + ", extra = " + extra);
        Message msg = timeHandler.obtainMessage(INFO);
        msg.arg1 = what;
        msg.arg2 = extra;
        timeHandler.sendMessage(msg);
        return true;
    }

    public boolean info(int what, int extra) {
        // TODO Auto-generated method stub
        switch (what) {
            case BVideoView.MEDIA_INFO_BUFFERING_START:
                Log.d("bvv", "info  startloading");
                startLoading();
                break;
            case BVideoView.MEDIA_INFO_BUFFERING_END:
                Log.i("bvv", "info stop loading");
                stopLoading();
                break;
            default:
//                Log.i("bvv", " stop loading  what:"+what);
//                stopLoading();
                break;
        }
        return false;
    }

    public boolean onError(int what, int extra) {
        // TODO Auto-generated method stub
        Log.i("bvv", "!!!error, what = " + what + ", extra = " + extra);
        Message msg = timeHandler.obtainMessage(ERROR);
        msg.arg1 = what;
        msg.arg2 = extra;
        timeHandler.sendMessage(msg);
        return true;
    }

    public boolean error(int what, int extra) {
        // TODO Auto-generated method stub
        Log.i("bvv", "error stop loading");
        loadingView.stopLoading();
        TipToast.getInstance(mContext).showToast(
                SkinManager.getResDrawable(R.drawable.toast_icon_tip),
                mContext.getString(R.string.player_error), doubleClickExitInterval, Gravity.CENTER);
        timeHandler.sendEmptyMessageDelayed(EXIT_PLAYER, doubleClickExitInterval);
        return true;
    }

    public void onCompletion() {
        // TODO Auto-generated method stub
        Log.i("bvv", "---PlayerView---------onCompletion");
        pressToExit = true;

        timeHandler.sendEmptyMessage(COMPLETION);
        try {
            wakeLock.release();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    public void completion() {
        // TODO Auto-generated method stub
        // showCompleteTip();
        exitPlayer();
    }

    public void onBufferingUpdate(int percent) {
        // TODO Auto-generated method stub
        // Log.i(tag, "onBufferingUpdate");
        Message msg = timeHandler.obtainMessage(BUFFERING_UPDATE);
        msg.arg1 = percent;
        timeHandler.sendMessage(msg);
    }

    public void bufferingUpdate(int percent) {
        // TODO Auto-generated method stub
        // if(paused)
        // return;
        // this.bufferProgress = percent * duration / 100;
        // Log.i("player_buffer", "buffer changed, time = "+bufferProgress);
        // if(bufferProgress > crtProgress)
        // {
        // loadingView.stopLoading();
        // }
        // else{
        // loadingView.startLoading();
        // }
    }

    public void resetInfo() {
        titleText.setText("");
        timeText.setText("--:--");
        hidePanel();
    }

    public void startLoading(String loadingStr) {
        tipView.hideTip();
        if (videoType != 1) {
            loadingView.setLoadingText(loadingStr);
            loadingView.startLoading();
        }
    }

    public void startLoading() {
        startLoading(mContext.getString(R.string.player_loading));
    }

    public void stopLoading() {
        if (!paused) {
            loadingView.stopLoading();
        }
    }

    // 如果是从手机端操作seek时，电视端需要弹出下方的面板，让用户看到在执行seek
    public void showSeekPanel(final int milliSeconds) {
        Log.d(tag, "showSeekPanel  crtProgress:" + crtProgress + " secondProgress:" + secondProgress + " duration:" + duration);
        if (seekCalled) // 如果是从电视端seek的，就不需要执行此方法
            return;
        ((Activity) mContext).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                timeText.setText(String.format("%s/%s", formatTime(crtProgress), durationStr));

                secondProgress = milliSeconds;
                float percent = (float) secondProgress / (float) duration;
                Log.i("pppp", "showSeekPanel  percent:" + percent);
                progressBar.setSecondProgress(percent);
                refreshProgressBar();
//                Log.d(tag, "showSeekPanel  startloading");
//                startLoading();

                int panelPosY = PlayerView.this.getMeasuredHeight()
                        - panelLayout.getMeasuredHeight();
                panelLayout.animate().y(panelPosY).setDuration(300);
                if (timeHandler.hasMessages(HIDE_PANEL_MSG_ID))
                    timeHandler.removeMessages(HIDE_PANEL_MSG_ID);
                timeHandler.sendEmptyMessageDelayed(HIDE_PANEL_MSG_ID, panelShowInterval);

                Log.i("seek", "showing float time text");
                setFloatTimeText(percent);
                panelDisplayed = true;
            }
        });
    }

    public void errorOccurred(final String errorType, final String videoName) {
        ((Activity) mContext).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                loadingView.stopLoading();
                String errorStr = "";
                switch (ERROT_TYPE.valueOf(errorType)) {
                    case PARSE_ERROR:
                        errorStr = mContext.getString(R.string.player_parse_error);
                        break;
                    case LIVE_UNSUPPORT_ERROR:
                        errorStr = mContext.getString(R.string.player_live_unsupport_error);
                        break;
                    case UNKNOWN_ERROR:
                        errorStr = mContext.getString(R.string.player_unknown_error);
                        break;
                }
                TipToast.getInstance(mContext).showToast(
                        SkinManager.getResDrawable(R.drawable.toast_icon_tip), errorStr,
                        doubleClickExitInterval, Gravity.CENTER);
                timeHandler.sendEmptyMessageDelayed(EXIT_PLAYER, doubleClickExitInterval);
            }
        });
    }

    public boolean processKeyDown(int keyCode) {
        if (panelDisplayed)
            delayPanelDisappear();
        if (keyCode != KeyEvent.KEYCODE_BACK)
            pressToExit = false;
        switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_LEFT:
                if (panelDisplayed)
                    adjustProgress(true);
                else
                    showPanel();
                return true;
            case KeyEvent.KEYCODE_DPAD_RIGHT:
                if (panelDisplayed)
                    adjustProgress(false);
                else
                    showPanel();
                return true;
            case KeyEvent.KEYCODE_DPAD_UP:
                showPanel();
                return true;
            case KeyEvent.KEYCODE_DPAD_DOWN:
                showPanel();
                return true;
            case KeyEvent.KEYCODE_DPAD_CENTER:
            case KeyEvent.KEYCODE_ENTER:
                if (playerExecutor != null) {
                    if (panelDisplayed && isSndPgsChanged) {
                        executeSeek(secondProgress);
                    } else {
                        if (playerExecutor.isPlaying())
                            playerExecutor.pause();
                        else {
                            if (netConnected)
                                playerExecutor.resume();
                            else {
                                paused = false;
                                tipView.showNetStatus();
                            }
                        }
                    }
                } else {
                    Log.i("key", "  executor = null");
                }
                return true;
            case KeyEvent.KEYCODE_BACK:
                if (panelDisplayed)
                    hidePanel();
                else {
                    if (pressToExit) {
                        exitPlayer();
                    } else {
                        // Toast.makeText(mContext, "再按一次退出", Toast.LENGTH_LONG).show();
                        String str = mContext.getString(R.string.press_again_to_exit);
                        Log.i(tag, "str = " + str);
                        TipToast.getInstance(mContext).showToast(
                                SkinManager.getResDrawable(R.drawable.toast_icon_tip), str,
                                doubleClickExitInterval, Gravity.BOTTOM);
                        pressToExit = true;
                        if (timeHandler.hasMessages(PRESS_TO_EXIT))
                            timeHandler.removeMessages(PRESS_TO_EXIT);
                        timeHandler.sendEmptyMessageDelayed(PRESS_TO_EXIT, doubleClickExitInterval);
                    }
                }
                return true;
        }
        return false;
    }

    private void executeSeek(int seekPos) {
        Log.i(tag, "seekTo, pos = " + seekPos);
        seekCalled = true;
        isSndPgsChanged = false;
        playerExecutor.seekTo(seekPos);
        progressBar.hideSecondProgress();
//        startLoading();
        tipView.hideTip();
    }

    private void adjustProgress(boolean left) {
        if (duration == 0)
            return;
        isSndPgsChanged = true;
        float percent = (float) secondProgress / (float) duration;
        if (left) {
            if (duration > 100)
                percent -= 0.01;
            else
                percent -= 1.1 / (float) duration;
            if (percent < 0)
                percent = 0;
        } else {
            if (duration > 100)
                percent += 0.01;
            else
                percent += 1.1 / (float) duration;
            if (percent > 1)
                percent = 1;
        }
        secondProgress = (int) (duration * percent);
        Log.i(tag, "adjustProgress  percent:" + percent);
        progressBar.setSecondProgress(percent);
        if (timeHandler.hasMessages(SEEK_MSG_ID))
            timeHandler.removeMessages(SEEK_MSG_ID);
        timeHandler.sendEmptyMessageDelayed(SEEK_MSG_ID, waitToSeekInterval);

        setFloatTimeText(percent);
    }

    private void setFloatTimeText(float percent) {
        floatTimeText.setText(formatTime(secondProgress));

        int totalWidth = progressBar.getMeasuredWidth();
        int timeTextWidth = floatTimeLayout.getMeasuredWidth();
        int arrowWidth = arrowImage.getMeasuredWidth();
        int floatTimeX = (int) (totalWidth * percent) - timeTextWidth / 2;
        if (floatTimeX < 0)
            floatTimeX = 0;
        else if (floatTimeX > totalWidth - timeTextWidth)
            floatTimeX = totalWidth - timeTextWidth;

        int floatArrowX = (int) (totalWidth * percent) - arrowWidth / 2;
        if (floatArrowX < 0)
            floatArrowX = 0;
        else if (floatArrowX > totalWidth - arrowWidth)
            floatArrowX = totalWidth - arrowWidth;
        LinearLayout.LayoutParams arrowParams = (LinearLayout.LayoutParams) arrowImage
                .getLayoutParams();
        arrowParams.leftMargin = floatArrowX - floatTimeX;

        LayoutParams timeParams = (LayoutParams) floatTimeLayout.getLayoutParams();
        timeParams.leftMargin = floatTimeX;
        floatTimeLayout.setVisibility(View.VISIBLE);
    }

    // 把毫秒数转换为hh:mm:ss的格式
    private String formatTime(int timeInMilliSeconds) {
//        timeInMilliSeconds = timeInMilliSeconds / 1000;
        int second = timeInMilliSeconds % 60;
        int minute = timeInMilliSeconds / 60;
        if (minute > 60) {
            int hour = minute / 60;
            minute = minute % 60;
            return String.format("%02d:%02d:%02d", hour, minute, second);
        } else {
            return String.format("%02d:%02d", minute, second);
        }
    }

    private static final int HIDE_PANEL_MSG_ID = 1;
    private static final int SEEK_MSG_ID = 2;
    private static final int SEEK_COMPLETE = 3;
    private static final int PROGRESS_CHANGED = 4;
    private static final int PLAY_STARTED = 5;
    private static final int PLAY_RESUMED = 6;
    private static final int PLAY_PAUSED = 7;
    private static final int PLAY_STOPPED = 8;
    private static final int ERROR = 9;
    private static final int INFO = 14;
    private static final int COMPLETION = 10;
    private static final int BUFFERING_UPDATE = 11;
    private static final int PRESS_TO_EXIT = 12;
    private static final int EXIT_PLAYER = 13;

    Handler timeHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            switch (msg.what) {
                case HIDE_PANEL_MSG_ID:
                    hidePanel();
                    break;
                case SEEK_MSG_ID:
                    if (playerExecutor != null) {
                        executeSeek(secondProgress);
                    }
                    break;
                case SEEK_COMPLETE:
                    seekComplete();
                    break;
                case PROGRESS_CHANGED:
                    progressChanged(msg.arg1);
                    break;
                case PLAY_STARTED:
                    playStarted((String) msg.obj, msg.arg1);
                    break;
                case PLAY_RESUMED:
                    playResumed();
                    break;
                case PLAY_PAUSED:
                    playPaused();
                    break;
                case ERROR:
                    error(msg.arg1, msg.arg2);
                    break;
                case INFO:
                    info(msg.arg1, msg.arg2);
                    break;
                case COMPLETION:
                    completion();
                    break;
                case BUFFERING_UPDATE:
                    bufferingUpdate(msg.arg1);
                    break;
                case PRESS_TO_EXIT:
                    pressToExit = false;
                    break;
                case EXIT_PLAYER:
                    exitPlayer();
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };

    private PlayerExecutor playerExecutor;

    public void setPlayerExecutor(PlayerExecutor executor) {
        this.playerExecutor = executor;
    }

    public interface PlayerExecutor {
        public void seekTo(int milliSeconds);

        public boolean isPlaying();

        public void pause();

        public void resume();

        public boolean hasNext();
    }

//    @Override
//    public void onNetStateChanged(boolean bConnected)
//    {
//        // TODO Auto-generated method stub
//        if (paused)
//        {
//            netConnected = bConnected;
//            return;
//        }
//        if (bConnected)
//        {
//            if (!netConnected)
//            {
//                netConnected = true;
//                seekCalled = true;
//                isSndPgsChanged = false;
//                playerExecutor.seekTo(crtProgress);
//                playerExecutor.resume();
//                Log.d(tag, "net changed  startloading");
//                startLoading();
//            }
//        } else
//        {
//            netConnected = false;
//            tipView.showNetStatus();
//            Log.d(tag, "net changed  stoploading");
//            stopLoading();
//        }
//    }

    public boolean isPaused() {
        return paused;
    }

    public void setNeedExitActivity(boolean flag) {
        needExitActivity = flag;
    }

    private boolean exitPlayerCalled = false;

    private void exitPlayer() {
        try {
            wakeLock.release();
        } catch (Exception e) {
            // TODO: handle exception
        }
        if (needExitActivity) {
            exitPlayerCalled = true;
            ((Activity) mContext).finish();
            backToLauncher();
        }
    }

    public void backToLauncher() {
//        try
//        {
//            ServiceFacotry.getAppService().startAppByPkgNameAndActivityName("com.tianci.appstore", "com.coocaa.launcher.EasyLauncherActivity");
//        } catch (RemoteException e)
//        {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } catch (ServiceNotConnectException e)
//        {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
    }
}
